package com.sunfeng.n8;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * 测试线程工具类创建线程
 * @author sunfeng
 * @date 2021/04/20 17:31
 **/
@Slf4j(topic = "c.TestThreadPoolExecutors")
public class TestThreadPoolExecutors {

    public static void main(String[] args) {
        testFixedThreadPool();




    }

    public static void  testSingleThreadExecutor(){
        /**
         * 如果有线程出现异常不会影响其他线程使用
         * 线程1发生异常之后会创建新的线程继续执行任务
         */
        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        threadPool.execute(()->{
            log.debug("1");
        });
        threadPool.execute(()->{
            int i=1/0;
            log.debug("2");
        });
        threadPool.execute(()->{
            log.debug("3");
        });
        threadPool.shutdown();

    }

    public static void  testCachedThreadPool(){
        //ThreadPoolExecutor(0, Integer.MAX_VALUE,
        //                                      60L, TimeUnit.SECONDS,
        //                                      new SynchronousQueue<Runnable>());
        /**
         * 核心线程数为0
         * 全部为救急线程
         * 救急线程
         *
         * SynchronousQueue 是没有容量的   它是没有容量的 没有线程来取是放不进去任务的
         */
        ExecutorService threadPool = Executors.newCachedThreadPool();


    }

    public static void  testFixedThreadPool(){
        ExecutorService threadPool = Executors.newFixedThreadPool(1);

        threadPool.execute(()->{
            log.debug("1");
        });
        threadPool.execute(()->{
            int i=1/0;
            log.debug("2");
        });
        threadPool.execute(()->{
            log.debug("3");
        });

        Future<String> submit = threadPool.submit(() -> {
            TimeUnit.SECONDS.sleep(1);
            return "孙峰";
        });
        try {
            String s = submit.get();
            log.debug(s);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }


        threadPool.shutdown();
    }
}
